package cn.jeeweb.modules.supervise.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ff.common.service.FFException;
import com.ff.common.util.format.DateUtil;
import com.ff.common.util.format.JsonConvert;
import com.ff.common.util.meta.DataFilterUtil;
import com.ff.common.util.validate.ValidatorUtil;

import cn.jeeweb.cache.MonitorTypeParaCache;
import cn.jeeweb.core.common.service.impl.CommonServiceImpl;
import cn.jeeweb.core.query.data.Condition.Operator;
import cn.jeeweb.core.query.data.Page;
import cn.jeeweb.core.query.data.PageRequest;
import cn.jeeweb.core.query.data.QueryRequest;
import cn.jeeweb.core.query.data.Queryable;
import cn.jeeweb.core.query.data.Sort.Direction;
import cn.jeeweb.core.query.wrapper.EntityWrapper;
import cn.jeeweb.core.utils.DateUtils;
import cn.jeeweb.modules.constant.AlarmTypeEnum;
import cn.jeeweb.modules.constant.DataResultConst;
import cn.jeeweb.modules.constant.DataValidConst;
import cn.jeeweb.modules.constant.MeasureCountConst;
import cn.jeeweb.modules.monitor.entity.McProItemAlarm;
import cn.jeeweb.modules.monitor.service.IMcProItemAlarmService;
import cn.jeeweb.modules.supervise.entity.McProItemMeasuringPoint;
import cn.jeeweb.modules.supervise.entity.McProItemMonitorItem;
import cn.jeeweb.modules.supervise.entity.McProItemRealTimeMonData;
import cn.jeeweb.modules.supervise.entity.McProject;
import cn.jeeweb.modules.supervise.mapper.McProItemRealTimeMonDataMapper;
import cn.jeeweb.modules.supervise.model.SumDataModel;
import cn.jeeweb.modules.supervise.service.IMcProItemMeasuringPointService;
import cn.jeeweb.modules.supervise.service.IMcProItemMonitorItemService;
import cn.jeeweb.modules.supervise.service.IMcProItemRealTimeMonDataService;
import cn.jeeweb.modules.supervise.service.IMcProjectService;
import cn.jeeweb.modules.webservice.UploadDataModel;

/**   
 * @Title: 项目监控-监测情况-实时监测数据
 * @Description: 项目监控-监测情况-实时监测数据
 * @author shawloong
 * @date 2017-11-21 16:32:11
 * @version V1.0   
 *
 */
@Transactional
@Service("mcProItemRealTimeMonDataService")
public class McProItemRealTimeMonDataServiceImpl  extends CommonServiceImpl<McProItemRealTimeMonDataMapper,McProItemRealTimeMonData> implements  IMcProItemRealTimeMonDataService {

	protected Logger log = Logger.getLogger(getClass());
	@Autowired
	private IMcProItemMeasuringPointService pointService;
	@Autowired
	private IMcProItemMonitorItemService itemSerivce;
	@Autowired
	private IMcProjectService projectSerivce;
	
	@Autowired
	private IMcProItemAlarmService alarmService;
	
	@Autowired 
	McProItemRealTimeMonDataMapper mcProItemRealTimeMonDataMapper;
	@Autowired
	private MonitorTypeParaCache monitorTypeParaCache;
	@Override
	public void create(UploadDataModel upload) {
		// TODO Auto-generated method stub
		McProItemMonitorItem item = itemSerivce.selectById(upload.getMonitorItemId());
		
		if(null == item)
		{
			log.warn("monitor item is not exist" + upload.getMonitorItemId());
			throw new FFException("监测项不存在："+upload.getMonitorItemId());
		}
		
		McProject project  = projectSerivce.selectById(item.getProjectId());
		
		if(project.getProjectCount() < upload.getCount())
		{
			project.setProjectCount(upload.getCount());
			projectSerivce.updateById(project);
 		}
		
		McProItemRealTimeMonData record = getLastestRecord(upload.getMonitorItemId());
		
		String isNew = MeasureCountConst.OLD;
		if(null != record && record.getProjectCount() < upload.getCount())
		{
			isNew = MeasureCountConst.NEW;
			updateCountStatus(upload.getMonitorItemId());
		}
		
		if(null != upload.getData())
		{
			for(McProItemRealTimeMonData e : upload.getData())
			{ 
				e.setNewProjectCount(isNew);
				
				Queryable query = QueryRequest.newQueryable();
				query.addCondition("monitorItemId", upload.getMonitorItemId());
				query.addCondition("measuringPointCode",e.getMeasuringPointCode());
 				
				McProItemMeasuringPoint point = pointService.get(query);
				if(null == point)
				{
					log.warn("point is not exist" + query.toString());
					throw new FFException("测点不存在："+e.getMeasuringPointCode());
				}
 				e.setMeasuringPointId(point.getId());
 				
 				e.setAlarmValue(toDouble(point.getAlarmValue()));
 				e.setWarnValue(toDouble(point.getWarningValue()));
 				e.setControlValue(toDouble(point.getControlValue()));
 				e.setRateAlarmValue(toDouble(point.getRateAlarmValue()));
 				e.setInitValue(point.getInitValue());
 				e.setInitialCumulativeValue(point.getInitialCumulativeValue());
  				
 				e.setUploadTime(upload.getUploadTime());
 				
 				e.setMonitorItemId(item.getId());
 				e.setMonitorItemName(item.getMonitorItemName());
 				e.setMonitorItemTypeCode(item.getGroupTypeCode());
 				e.setMonitorItemTypeName(item.getGroupTypeName());
 				e.setProjectId(project.getId());
 				e.setProjectName(project.getName());
 				e.setProjectCount(upload.getCount());
				List<McProItemRealTimeMonData> deptDataList = JsonConvert.jsonToObject(e.getDepthExt(), List.class,McProItemRealTimeMonData.class);

				if(!ValidatorUtil.isEmpty(deptDataList))
				{
					for(McProItemRealTimeMonData temp :deptDataList)
					{
						temp.setMeasuringPointCode(e.getMeasuringPointCode());
						temp.setMeasuringPointId(e.getMeasuringPointId());
						temp.setMonitorItemName(e.getMonitorItemName());
						temp.setUploadTime(e.getUploadTime());
						temp.setCollectTime(e.getCollectTime());
						temp.setDataValid(e.getDataValid());
						temp.setProjectCount(e.getProjectCount());
						temp.setTest(e.getTest());
					}
				}
 				 
 				{
 					 
 					int time = 1;
 					try
 					{
 						time = Integer.valueOf(point.getInitialValueTimes());
 		 			}
 					catch(Exception ex)
 					{
 						log.error("error"+point.getInitialValueTimes());
 		 			}
  					if(e.getProjectCount() <= time)
 	 				{
 	 					
  						//setInitValue(e, point, deptDataList);
  						
  	 					
 	 				}
 	 				else
 	 				{
 	 					McProItemRealTimeMonData last = getLastRecord(point.getId(),e.getProjectCount());
 	 					if(null == last)
 	 					{
 	 						//setInitValue(e, point, deptDataList);
 	 						
 	 						 
 	 					}
 	 					else
 	 					{
 	 						if(monitorTypeParaCache.isShift(point.getMonitorItemTypeCode()))
 	 	 					{
 	 	 						List<McProItemRealTimeMonData> lastDeptDataList = JsonConvert.jsonToObject(last.getDepthExt(), List.class,McProItemRealTimeMonData.class);

  	 	 						List<McProItemMeasuringPoint> initDeptList = JsonConvert.jsonToObject(point.getDepthExt(), List.class,McProItemMeasuringPoint.class);

 	 	 						if(!ValidatorUtil.isEmpty(deptDataList))
 	 	 						{
 	 	 							for(McProItemRealTimeMonData temp : deptDataList)
 	 	 	 						{
 	 	 	 							McProItemRealTimeMonData lastDept = DataFilterUtil.getObjFromList(lastDeptDataList, "depthExt", temp.getDepthExt());
 	 	 	 							McProItemMeasuringPoint initDept = DataFilterUtil.getObjFromList(initDeptList, "depthExt", temp.getDepthExt());
 	 	 	 							if(null != initDept)
 	 	 	 							{
 	 	 	 								temp.setInitValue(initDept.getInitValue());
 	 	 	 	 							temp.setInitialCumulativeValue(initDept.getInitialCumulativeValue());
 	  	 	 							}
 	 	 	 							if(null != lastDept)
 	 	 	 							{
 	 	 	 								calcData(temp,lastDept, point);
 	 	 	 							}
 	 	 	 						
 	 	 	 						}
 	 	 	 						McProItemRealTimeMonData maxNow = DataFilterUtil.getAbsMaxMinObjFromList(deptDataList,"nowValue",true);
 	 	 	 						McProItemRealTimeMonData maxMinus = DataFilterUtil.getAbsMaxMinObjFromList(deptDataList,"minusValue",true);
 	 	 	 						McProItemRealTimeMonData maxSum = DataFilterUtil.getAbsMaxMinObjFromList(deptDataList,"sumValue",true);
 	 	 	 						McProItemRealTimeMonData maxChangeRate = DataFilterUtil.getAbsMaxMinObjFromList(deptDataList,"changeRate",true);
 	 	 	 						if(null != maxNow)
 	 	 	 						{
 	 	 	 	 						e.setNowValue(maxNow.getNowValue());
 	 	 	 	 						e.setNowValueDepth(maxNow.getDepthExt());
 	  	 	 						}
 	 	 	 						if(null != maxMinus)
 	 	 	 						{
 	 	 	 	 						e.setMinusValue(maxMinus.getMinusValue());
 	 	 	 	 						e.setMinusValueDepth(maxMinus.getDepthExt());
 	  	 	 						}
 	 	 	 						if(null != maxSum)
 	 	 	 						{
 	 	 	 	 						e.setSumValue(maxSum.getSumValue());
 	 	 	 	 						e.setSumValueDepth(maxSum.getDepthExt());
 	  	 	 						}
 	 	 	 						if(null != maxChangeRate)
 	 	 	 						{
 	 	 	 	 						e.setChangeRate(maxChangeRate.getChangeRate());
 	 	 	 	 						e.setChangeRateDepth(maxChangeRate.getDepthExt());
 	  	 	 						}
 	 	 	 						e.setDepthExt(JsonConvert.ObjectToJson(deptDataList));
 	 	 						}
 	 	 						
 	 	 					}
 	 	 					else
 	 	 					{
 	 	 						calcData(e,last, point);
 	 	 					}
 	 					}
   	 				}
 					Map<String, Object> columnMap = new HashMap<>();
	 				columnMap.put("measuring_point_id", e.getMeasuringPointId());
	 				columnMap.put("project_count", e.getProjectCount());
					this.deleteByMap(columnMap );
					this.createAlarm(e, point,false);
 					this.insert(e);
 					pointService.updateById(point);
 				}
   				
 			}
		}
		
	}

	private void setInitValue(McProItemRealTimeMonData e, McProItemMeasuringPoint point,
			List<McProItemRealTimeMonData> deptDataList,boolean ignoreTime)
	{
		int time = 1;
		if(!ignoreTime)
		{
			try 
			{
				time = Integer.valueOf(point.getInitialValueTimes());
			} 
			catch (Exception ex) 
			{
				log.error("error" + point.getInitialValueTimes());
			}
		}
		
		if(monitorTypeParaCache.isShift(point.getMonitorItemTypeCode()))
		{
				List<McProItemMeasuringPoint> initDeptList = JsonConvert.jsonToObject(point.getDepthExt(), List.class,McProItemMeasuringPoint.class);
 
				if(null != initDeptList)
				{
					for(McProItemMeasuringPoint temp : initDeptList)
					{
						McProItemRealTimeMonData dept = DataFilterUtil.getObjFromList(deptDataList, "depthExt", temp.getDepthExt());
						if(null != dept)
						{
							dept.setSumValue(dept.getInitialCumulativeValue());
							
							double d = 0.0;
							if(e.getTestCount() == 1 || time==1)
							{
								d = dept.getNowValue()/time;
							}
							else
							{
								d = dept.getNowValue()/time + temp.getInitValue();
							}
							temp.setInitValue(d);
 							
							dept.setInitValue(d);
							temp.setInitValueId(dept.getId());
							temp.setXvalue(dept.getXvalue());
							temp.setYvalue(dept.getYvalue());
						}
						
					}
				}
				
				 
				
			McProItemRealTimeMonData maxNow = DataFilterUtil.getAbsMaxMinObjFromList(deptDataList, "nowValue", true);
			McProItemRealTimeMonData maxMinus = DataFilterUtil.getAbsMaxMinObjFromList(deptDataList, "minusValue",
					true);
			McProItemRealTimeMonData maxSum = DataFilterUtil.getAbsMaxMinObjFromList(deptDataList, "sumValue", true);
			McProItemRealTimeMonData maxChangeRate = DataFilterUtil.getAbsMaxMinObjFromList(deptDataList, "changeRate",
					true);
			if (null != maxNow) {
				e.setNowValue(maxNow.getNowValue());
				e.setNowValueDepth(maxNow.getDepthExt());
			}
			if (null != maxMinus) {
				e.setMinusValue(maxMinus.getMinusValue());
				e.setMinusValueDepth(maxMinus.getDepthExt());
			}
			if (null != maxSum) {
				e.setSumValue(maxSum.getSumValue());
				e.setSumValueDepth(maxSum.getDepthExt());
			}
			if (null != maxChangeRate) {
				e.setChangeRate(maxChangeRate.getChangeRate());
				e.setChangeRateDepth(maxChangeRate.getDepthExt());
			}
			point.setDepthExt(JsonConvert.ObjectToJson(initDeptList));
			e.setDepthExt(JsonConvert.ObjectToJson(deptDataList));
		}
		else
		{
			
			e.setSumValue(point.getInitialCumulativeValue());
			double d = 0;
			if(e.getTestCount() == 1|| time==1)
			{
				d = e.getNowValue()/time;
			}
			else
			{
				d = e.getNowValue()/time + point.getInitValue();
			}
			e.setInitValue(d);
			point.setInitValue(d);
			point.setInitValueId(e.getId());
			point.setXvalue(e.getXvalue());
			point.setYvalue(e.getYvalue());
		}
	}
	private void setInitValue(McProItemRealTimeMonData e, McProItemMeasuringPoint point,
			List<McProItemRealTimeMonData> deptDataList) {
		
		this.setInitValue(e, point, deptDataList,false);
	}

	private void calcData(McProItemRealTimeMonData e,McProItemRealTimeMonData last,
			McProItemMeasuringPoint point) {
 		{
			Double ratio = monitorTypeParaCache.getRatio(point.getMonitorItemTypeCode());
			e.setLastValue(last.getNowValue());
			e.setMinusValue((e.getNowValue()-e.getLastValue())*ratio);
			
			Date now = DateUtil.stringToDate(DateUtil.DateToString(e.getUploadTime(),"yyyy-MM-dd"));
			Date end = DateUtil.stringToDate(DateUtil.DateToString(last.getUploadTime(),"yyyy-MM-dd"));

			double days =   DateUtils.getDistanceOfTwoDate(end,now);
			if(days < 1)
			{
				days = 1;
			}
			e.setChangeRate(Math.abs(e.getMinusValue()/days));
			e.setSumValue((e.getNowValue()- e.getInitValue())*ratio + e.getInitialCumulativeValue());
		}
	}
	
	private McProItemRealTimeMonData getLastestRecord(String monitorItemId)
	{
		Queryable query = QueryRequest.newQueryable();
		query.addCondition("monitorItemId", monitorItemId);
 		query.addOrder(Direction.DESC,"projectCount");
		
		query.setPageable(new PageRequest(1,1));
		
		Page<McProItemRealTimeMonData> dataList = this.list(query);
		
		if(ValidatorUtil.isEmpty(dataList.getContent()))
		{
			return null;
		}
		return dataList.getContent().get(0);
 	}
	private void updateCountStatus(String monitorItemId)
	{
		Queryable query = QueryRequest.newQueryable();
		query.addCondition("monitorItemId", monitorItemId);
		query.addCondition("newProjectCount", MeasureCountConst.NEW);
 		
 		
		List<McProItemRealTimeMonData> dataList = this.listWithNoPage(query);
		if(!ValidatorUtil.isEmpty(dataList))
		{
			for(McProItemRealTimeMonData e : dataList)
			{
				e.setNewProjectCount(MeasureCountConst.OLD);
			}
			this.updateBatchById(dataList);
 		}
		
		List<McProItemAlarm> entityList = alarmService.listWithNoPage(query);
		if(!ValidatorUtil.isEmpty(entityList))
		{
			for(McProItemAlarm e : entityList)
			{
				e.setNewProjectCount(MeasureCountConst.OLD);
			}
			alarmService.updateBatchById(entityList);
 		}
		
		
   	}
	private McProItemRealTimeMonData getLastRecord(String measuringPointId,int count)
	{
		Queryable query = QueryRequest.newQueryable();
		query.addCondition("measuringPointId", measuringPointId);
		query.addCondition("dataResult", DataResultConst.use);
		query.getCondition().and(Operator.lt, "projectCount", count);
		query.addOrder(Direction.DESC,"projectCount");
		
		query.setPageable(new PageRequest(1,1));
		
		Page<McProItemRealTimeMonData> dataList = this.list(query);
		
		if(ValidatorUtil.isEmpty(dataList.getContent()))
		{
			return null;
		}
		return dataList.getContent().get(0);
 	}
	private Double toDouble(String val)
	{
		Double d = 0.0;
		
		try
		{
			d = Double.valueOf(val);
		}
		catch(Exception e)
		{
			log.error("convert failed",e);
		}
 		
		return d;
	}
	
	private McProItemAlarm createAlarm(McProItemRealTimeMonData data,McProItemMeasuringPoint point,boolean isCreate)
	{
		if("1".equals(point.getDebug()))
		{
	       isCreate = false;
		}
		McProItemAlarm alarm = new McProItemAlarm();
		alarm.setMeasuringPointId(data.getMeasuringPointId());
		alarm.setMeasuringPointCode(data.getMeasuringPointCode());
		alarm.setMonitorItemId(data.getMonitorItemId());
		alarm.setMonitorItemName(data.getMonitorItemName());
 		alarm.setMonitorTypeCode(data.getMonitorItemTypeCode());
		alarm.setMonitorTypeName(data.getMonitorItemTypeName());
		alarm.setProjectId(data.getProjectId());
		alarm.setProjectName(data.getProjectName());
		alarm.setProjectCount(data.getProjectCount());
		alarm.setTestCount(data.getTestCount());
		alarm.setNewProjectCount(data.getNewProjectCount());
		alarm.setInitValue(data.getInitValue());
		alarm.setSumValue(data.getSumValue());
		alarm.setChangeRate(data.getChangeRate());
		alarm.setMinusValue(data.getMinusValue());
		alarm.setLastValue(data.getLastValue());
		alarm.setNowValue(data.getNowValue());
		alarm.setAlarmKind(AlarmTypeEnum.SUM_ALARM);
		
		alarm.setWarnValue(data.getWarnValue());
		alarm.setControlValue(data.getControlValue());
		alarm.setAlarmValue(data.getAlarmValue());
		alarm.setRateAlarmValue(data.getRateAlarmValue());
		alarm.setDataId(data.getId());
		
		double sumValue = data.getSumValue();

		if(ValidatorUtil.isEmpty(point.getAlarmValueNg()))
		{
			sumValue = Math.abs(sumValue);
			if(alarm.getControlValue()>0 && sumValue > alarm.getControlValue())
			{
				alarm.setAlarmTypeName(AlarmTypeEnum.OVERLOAD.getName());
				alarm.setAlarmTypeId(AlarmTypeEnum.OVERLOAD.getValue());
				data.setMeasuringResult(AlarmTypeEnum.OVERLOAD.getName());

			}
			else if( alarm.getAlarmValue()>0 && sumValue > alarm.getAlarmValue())
			{
				alarm.setAlarmTypeName(AlarmTypeEnum.ALARM.getName());
				alarm.setAlarmTypeId(AlarmTypeEnum.ALARM.getValue());
				data.setMeasuringResult(AlarmTypeEnum.ALARM.getName());

			}
			else if(alarm.getWarnValue()>0 && sumValue > alarm.getWarnValue())
			{
				alarm.setAlarmTypeName(AlarmTypeEnum.WARN.getName());
				alarm.setAlarmTypeId(AlarmTypeEnum.WARN.getValue());
				data.setMeasuringResult(AlarmTypeEnum.WARN.getName());

			}
			else
			{
				data.setMeasuringResult(AlarmTypeEnum.NORMAL.getName());
			}
 		}
		else
		{
			if(alarm.getControlValue()>0 && (sumValue > alarm.getControlValue() || sumValue<-toDouble(point.getControlValueNg())))
			{
				alarm.setAlarmTypeName(AlarmTypeEnum.OVERLOAD.getName());
				alarm.setAlarmTypeId(AlarmTypeEnum.OVERLOAD.getValue());
				data.setMeasuringResult(AlarmTypeEnum.OVERLOAD.getName());

			}
			else if( alarm.getAlarmValue()>0 && (sumValue > alarm.getAlarmValue() || sumValue<-toDouble(point.getAlarmValueNg())))
			{
				alarm.setAlarmTypeName(AlarmTypeEnum.ALARM.getName());
				alarm.setAlarmTypeId(AlarmTypeEnum.ALARM.getValue());
				data.setMeasuringResult(AlarmTypeEnum.ALARM.getName());
 			}
			else if(alarm.getWarnValue()>0 && (sumValue > alarm.getWarnValue()|| sumValue<-toDouble(point.getWarnValueNg())))
			{
				alarm.setAlarmTypeName(AlarmTypeEnum.WARN.getName());
				alarm.setAlarmTypeId(AlarmTypeEnum.WARN.getValue());
				data.setMeasuringResult(AlarmTypeEnum.WARN.getName());

			}
			else
			{
				data.setMeasuringResult(AlarmTypeEnum.NORMAL.getName());
			}
		}
		
		 
		 
		 if(isCreate)
		 {
			 if(!AlarmTypeEnum.NORMAL.getName().equals(data.getMeasuringResult()))
			 {
						alarmService.insert(alarm);
						//触发更新project
						projectSerivce.updateCount(alarm.getProjectId(), alarm.getAlarmTypeId());
			 }
		 }
		 
		 
	 
		McProItemAlarm rateAlarm =  JsonConvert.jsonToObject(JsonConvert.ObjectToJson(alarm), McProItemAlarm.class);
		rateAlarm.setId(null);
		rateAlarm.setAlarmKind(AlarmTypeEnum.RATE_ALARM);
		if( data.getRateAlarmValue()  > 0 )
		{
			if(data.getChangeRate() >  data.getRateAlarmValue())
			{
				rateAlarm.setAlarmTypeName(AlarmTypeEnum.ALARM.getName());
				rateAlarm.setAlarmTypeId(AlarmTypeEnum.ALARM.getValue());
				if(isCreate)
				{
					alarmService.insert(rateAlarm);
					projectSerivce.updateCount(alarm.getProjectId(), alarm.getAlarmTypeId());

				} 
			}
		}
		return alarm;
  		
	}

	@Override
	public void valid(UploadDataModel upload) {
		// TODO Auto-generated method stub
		
		McProItemMonitorItem item = itemSerivce.selectById(upload.getMonitorItemId());
		
		if(null == item)
		{
			log.warn("monitor item is not exist" + upload.getMonitorItemId());
			throw new FFException("监测项不存在："+upload.getMonitorItemId());
		}
		List<McProItemAlarm> controlList = new ArrayList<McProItemAlarm>();
		List<McProItemAlarm> alarmList = new ArrayList<McProItemAlarm>();
		List<McProItemAlarm> warnList = new ArrayList<McProItemAlarm>();
		if(null != upload.getData())
		{
			List<McProItemRealTimeMonData> oldList =new ArrayList<McProItemRealTimeMonData>();
			for(McProItemRealTimeMonData e : upload.getData())
			{
				McProItemRealTimeMonData old = this.selectById(e.getId());
				
				
				if(null != old)
				{
					int testCount = 0;
	 				McProItemRealTimeMonData last = getLastRecord(old.getMeasuringPointId(),old.getProjectCount());

					//McProItemRealTimeMonData last = getLastValidRecord(old.getMeasuringPointId());
					if(null != last)
					{
						if(null != last.getTestCount())
						{
							testCount = last.getTestCount();
						}
							
					}
					
					Queryable query = QueryRequest.newQueryable();
					query.addCondition("monitorItemId", upload.getMonitorItemId());
					query.addCondition("measuringPointCode",old.getMeasuringPointCode());
	 				
					McProItemMeasuringPoint point = pointService.get(query);
					if(null == point)
					{
						log.warn("point is not exist" + query.toString());
						throw new FFException("测点不存在："+old.getMeasuringPointCode());
					}
					
  					
					
					
					old.setFlag(e.getFlag());
					old.setTestCount(testCount);
					old.setDataValid(e.getDataValid());
 					List<McProItemRealTimeMonData> deptDataList = JsonConvert.jsonToObject(old.getDepthExt(), List.class,McProItemRealTimeMonData.class);

					if(DataValidConst.retest.equals(e.getDataValid())||DataValidConst.valid.equals(e.getDataValid()))
					{
						testCount++;
						
						old.setDataResult(DataResultConst.use);
						old.setTestCount(testCount);
						
						if(DataValidConst.retest.equals(e.getDataValid()))
						{
							if(null != last)
		 					{
		 	 					
		 	 					old.setSumValue(last.getSumValue());
	 	 					} 
		 					old.setMinusValue(0.0);
		 					old.setChangeRate(0.0);
		 					old.setInitialCumulativeValue(old.getSumValue());
		 					
		 					List<McProItemRealTimeMonData> lastDeptDataList = JsonConvert.jsonToObject(last.getDepthExt(), List.class,McProItemRealTimeMonData.class);
		 					List<McProItemMeasuringPoint> pointList = JsonConvert.jsonToObject(point.getDepthExt(), List.class,McProItemMeasuringPoint.class);

		 					
		 					point.setInitialCumulativeValue(old.getSumValue());
		 					
		 					if(monitorTypeParaCache.isShift(point.getMonitorItemTypeCode()))
		 					{
		 						for(McProItemRealTimeMonData lastDept : lastDeptDataList)
								{
									McProItemRealTimeMonData dept = DataFilterUtil.getObjFromList(deptDataList, "depthExt", lastDept.getDepthExt());
									McProItemMeasuringPoint temp = DataFilterUtil.getObjFromList(pointList, "depthExt", lastDept.getDepthExt());

									if(null != temp)
									{
										temp.setInitialCumulativeValue(lastDept.getInitialCumulativeValue());
										temp.setInitValue(0.0);
									}
									if(null != dept)
									{
										dept.setInitialCumulativeValue(lastDept.getSumValue());
									}
									
								}
			 					point.setDepthExt(JsonConvert.ObjectToJson(pointList));
			 					old.setDepthExt(JsonConvert.ObjectToJson(deptDataList));
		 					}
		 					
		 					point.setInitValue(0.0);
		 					this.setInitValue(old, point, deptDataList,true);
		 					
		 					
		 					
		 					
						}
						else
						{
							int time = 1;
		 					try
		 					{
		 						time = Integer.valueOf(point.getInitialValueTimes());
		 		 			}
		 					catch(Exception ex)
		 					{
		 						log.error("error"+point.getInitialValueTimes());
		 		 			}
		  					if(testCount <= time)
		 	 				{
	 	  						setInitValue(old, point, deptDataList);
	 	 	 				}
						}
						pointService.updateById(point);
	  					
						old.setDataResult(DataResultConst.use);
						old.setTestCount(testCount);
						McProItemAlarm alarm = this.createAlarm(old, point,true);
						
						if(AlarmTypeEnum.OVERLOAD.getValue().equals(alarm.getAlarmTypeId()))
						{
							controlList.add(alarm);
						}
						else if(AlarmTypeEnum.ALARM.getValue().equals(alarm.getAlarmTypeId()))
						{
							alarmList.add(alarm);
						}
						else if(AlarmTypeEnum.WARN.getValue().equals(alarm.getAlarmTypeId()))
						{
							warnList.add(alarm);
						}
					}
					else
					{
						old.setDataResult(DataResultConst.no_use);
					}
					
					
	 				 
	 					
					oldList.add(old);
				}
			}
			alarmService.sendMessage(item, alarmList);
			alarmService.sendMessage(item, warnList);
			alarmService.sendMessage(item, controlList);
			if(!oldList.isEmpty())
			{
				this.updateBatchById(oldList);
			}
			
		}
	}
	
 
	private McProItemRealTimeMonData getLastValidRecord(String measuringPointId)
	{
		Queryable query = QueryRequest.newQueryable();
		query.addCondition("measuringPointId", measuringPointId);
		query.addCondition("dataResult", DataResultConst.use);

 		query.addOrder(Direction.DESC,"testCount");
 		
		
		query.setPageable(new PageRequest(1,1));
		
		Page<McProItemRealTimeMonData> dataList = this.list(query);
		
		if(ValidatorUtil.isEmpty(dataList.getContent()))
		{
			return null;
		}
		return dataList.getContent().get(0);
 	}
	
	private List<McProItemRealTimeMonData> getSumByFiled(String projectId,String field,boolean isMin,String monitorItemId,String projectCount)
	{
		EntityWrapper<McProItemRealTimeMonData> entityWrapper = new EntityWrapper<McProItemRealTimeMonData>(McProItemRealTimeMonData.class);
		if(ValidatorUtil.isEmpty(projectCount))
		{
			entityWrapper.eq("new_project_count", MeasureCountConst.NEW);
 		}
		else
		{
			entityWrapper.eq("project_count", projectCount);
		}
		if(!ValidatorUtil.isEmpty(monitorItemId))
		{
			entityWrapper.eq("monitor_item_id", monitorItemId);

		}
		entityWrapper.eq("project_id", projectId);
		entityWrapper.orderBy(field, isMin);
 		List<McProItemRealTimeMonData> dataList = mcProItemRealTimeMonDataMapper.getSumData(entityWrapper);
		return dataList;
	}
	

	public List<SumDataModel> getSumData(String projectId,String monitorItemId,String projectCount )
	{
 
 		List<McProItemRealTimeMonData> minList = getSumByFiled(projectId,"sum_value",true,monitorItemId,projectCount);
 		List<McProItemRealTimeMonData> maxList = getSumByFiled(projectId,"sum_value",false, monitorItemId,projectCount);
 		//List<McProItemRealTimeMonData> minRateList = getSumByFiled(projectId,"change_rate",true);
 		List<McProItemRealTimeMonData> maxRateList = getSumByFiled(projectId,"change_rate",false, monitorItemId,projectCount);
 		
 		Queryable queryable = QueryRequest.newQueryable();
 		if(null != monitorItemId)
 		{	
 			queryable.addCondition("id", monitorItemId);
 		}
 		queryable.addCondition("projectId", projectId);
		List<McProItemMonitorItem> itemList = itemSerivce.listWithNoPage(queryable );
		
		EntityWrapper<McProItemAlarm> entityWrapper = new EntityWrapper<McProItemAlarm>(McProItemAlarm.class);
		if(ValidatorUtil.isEmpty(projectCount))
		{
			entityWrapper.eq("new_project_count", MeasureCountConst.NEW);
 		}
		else
		{
			entityWrapper.eq("project_count", projectCount);
		}
 		entityWrapper.eq("project_id", projectId);
		entityWrapper.ge("alarm_type_id",AlarmTypeEnum.ALARM.getValue());
 		
 		List<McProItemAlarm> alarmList = alarmService.selectList(entityWrapper);
 		

		List<SumDataModel> dataList = new ArrayList<>();
		for(McProItemRealTimeMonData data :minList)
		{
			SumDataModel model = new SumDataModel();
			 
			model.setMonitorItemId(data.getMonitorItemId());
			model.setMonitorItemName(data.getMonitorItemName());
			model.setMaxName(monitorTypeParaCache.getMaxNameUnit(data.getMonitorItemTypeCode()));
			model.setMinName(monitorTypeParaCache.getMinNameUnit(data.getMonitorItemTypeCode()));
			model.setRateName(monitorTypeParaCache.getMaxRateUnit(data.getMonitorItemTypeCode()));
 			 
 			model.setMinData(data);
			model.setMaxData(DataFilterUtil.getObjFromList(maxList, "monitorItemId", data.getMonitorItemId()));
			
 		 
 			if(model.getMaxData().getSumValue() > 0)
			{
				model.setMaxValue(String.format("%.1f", model.getMaxData().getSumValue()));
				model.setMaxPoint(model.getMaxData().getMeasuringPointCode());
			}
			if(model.getMinData().getSumValue() < 0)
			{
				model.setMinValue(String.format("%.1f",model.getMinData().getSumValue()));
				model.setMinPoint(model.getMinData().getMeasuringPointCode());
			}
 
			//设置速率值
			McProItemRealTimeMonData maxRate = DataFilterUtil.getObjFromList(maxRateList, "monitorItemId", data.getMonitorItemId());
			if(null != maxRate)
			{
				model.setRateValue(String.format("%.2f",maxRate.getChangeRate()));

 				model.setRatePoint(maxRate.getMeasuringPointCode());
 			}
			
			//设置报警值
			McProItemMonitorItem item = DataFilterUtil.getObjFromList(itemList, "id", data.getMonitorItemId());
			if(null != item)
			{
				model.setAlarmValue(item.getTotalAlarmValue());
				model.setControlValue(item.getTotalControlValue());
				model.setRateAlarmValue(item.getRateChangeAlarmValue());
				model.setRateControlValue(item.getRateChangeControlValue());
			}
			
			
			//设置报警点
			List<McProItemAlarm> temp = DataFilterUtil.getObjListFromList(alarmList, "monitorItemId", data.getMonitorItemId());
			String point = "";
			if(ValidatorUtil.isEmpty(temp))
			{
				model.setAlarmStatus( AlarmTypeEnum.NORMAL.getName());
			}
			else
			{
				model.setAlarmStatus( AlarmTypeEnum.ALARM.getName());
				for(McProItemAlarm alarm: temp)
				{
					point += alarm.getMeasuringPointCode() + "(" + alarm.getSumValue() + monitorTypeParaCache.get(data.getMonitorItemTypeCode()).getUnit() + "),\n";
	 				if(alarm.getAlarmTypeId() == AlarmTypeEnum.OVERLOAD.getValue())
	 				{
	 					model.setAlarmStatus(alarm.getAlarmTypeName());
	 				}
	 			}
			}
			
			
			model.setAlarmPoint(point);
			
			
			dataList.add(model);
		}
		
		return dataList;
	}
 
}
